package com.cryrabbit.bmbhome.ui;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.cryrabbit.bmbhome.R;
import com.cryrabbit.bmbhome.Service.MyService;
import com.cryrabbit.bmbhome.utils.RealtimeTrackData;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by CryRabbit on 2016/7/14.
 */
public class GuijiActivity extends Activity{
    private MyService.MyBinder binder;
    private MapView mapView = null;
    private BaiduMap baiduMap = null;
    private MapStatusUpdate msUpdate = null;
    private BitmapDescriptor realtimeBitmap;  //图标
    private OverlayOptions overlay;  //覆盖物
    private List<LatLng> pointList = new ArrayList<LatLng>();  //定位点的集合
    private PolylineOptions polyline = null;  //路线覆盖物
    private ServiceConnection conn2=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder=(MyService.MyBinder)service;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    String a=binder.get();
                    if(a!=null){
                        showRealtimeTrack(a);
                    }
                }
            },0,5000);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_pager_two);
        init();
        LocationManager locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        boolean a=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(a==false){
            AlertDialog.Builder builder=new AlertDialog.Builder(GuijiActivity.this);
            builder.setTitle("GPS异常")
                    .setMessage("为了更准确的记录，请到\"位置信息\"中。选择模式为\"准确度高\"。")
                    .setPositiveButton("开启GPS", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent=new Intent();
                            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
            builder.show();
        }
    }
    private void init() {
        mapView = (MapView) findViewById(R.id.baidumap);
        baiduMap = mapView.getMap();
        mapView.showZoomControls(false);
        Intent intent=new Intent(GuijiActivity.this,MyService.class);
        bindService(intent,conn2, Service.BIND_AUTO_CREATE);
        startService(intent);
    }
    protected void showRealtimeTrack(String realtimeTrack){
        //数据以JSON形式存取
        RealtimeTrackData realtimeTrackData = new Gson().fromJson(realtimeTrack, RealtimeTrackData.class);

        if(realtimeTrackData != null && realtimeTrackData.getStatus() ==0){

            LatLng latLng = realtimeTrackData.getRealtimePoint();

            if(latLng != null){
                pointList.add(latLng);
                drawRealtimePoint(latLng);
            }
            else{
                Toast.makeText(getApplicationContext(), "当前无轨迹点", Toast.LENGTH_LONG).show();
            }

        }

    }

    @Override
    public void finish() {
        super.finish();
    }

    /**
     * 画出实时线路点
     * @param point
     */
    private void drawRealtimePoint(LatLng point){

        baiduMap.clear();
        MapStatus mapStatus = new MapStatus.Builder().target(point).zoom(18).build();
        msUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
        realtimeBitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
        overlay = new MarkerOptions().position(point)
                .icon(realtimeBitmap).zIndex(9).draggable(true);

        if(pointList.size() >= 2  && pointList.size() <= 1000){
            polyline = new PolylineOptions().width(10).color(Color.RED).points(pointList);
        }
        addMarker();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn2);
    }

    private void addMarker(){
        if(msUpdate != null){
            baiduMap.setMapStatus(msUpdate);
        }

        if(polyline != null){
            baiduMap.addOverlay(polyline);
        }

        if(overlay != null){
            baiduMap.addOverlay(overlay);
        }
    }
}
